package com.riku.security.service.impl;

import com.riku.security.mapper.SeMenuMapper;
import com.riku.security.model.SeMenu;
import com.riku.security.model.SeSecurityQuery;
import com.riku.security.service.SeMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by NANC on 2021/5/16.
 */
@Service
public class SeMenuServiceImpl implements SeMenuService{
    @Autowired
    private SeMenuMapper seMenuMapper;

    @Override
    public void insertMenu(SeMenu seMenu) {
        seMenuMapper.insert(seMenu);
    }

    @Override
    public void deleteMenu(Long id) {
        seMenuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void updateMenu(SeMenu seMenu) {
        seMenuMapper.updateByPrimaryKeySelective(seMenu);
    }

    @Override
    public List<SeMenu> selectMenuPage(String serviceCode,String menuName) {
        SeMenu query = new SeMenu();
        query.setServiceCode(serviceCode);
        query.setMenuName(menuName);

        List<SeMenu> list = seMenuMapper.selectMenuByName(query);
        return list;
    }

    @Override
    public List<SeMenu> selectMenuApiPage(String serviceCode, Long parentId, String menuName) {
        SeMenu query = new SeMenu();
        query.setServiceCode(serviceCode);
        query.setParentId(parentId);
        query.setMenuName(menuName);

        List<SeMenu> list = seMenuMapper.selectApiByName(query);
        return list;
    }

    @Override
    public List<SeMenu> selectMenuTree(String serviceCode,Integer includeApi) {
        SeSecurityQuery query = new SeSecurityQuery();
        query.setIncludeApi(includeApi);
        query.setServiceCode(serviceCode);
        List<SeMenu> menuList = seMenuMapper.selectMenuAndApiByServiceCode(query);

        List<SeMenu> retList = getTree(menuList,null);
        return retList;
    }

    private List<SeMenu> getTree(List<SeMenu> list, Long parentId) {
        List<SeMenu> result = list
                .stream()
                .filter(node -> null == parentId ? parentId == node.getParentId() : parentId.equals(node.getParentId()))
                .map(node -> {
                    node.setChildList(getTree(list, node.getId()));
                    return node;
                })
                .collect(Collectors.toList());
        return result;
    }

    @Override
    public List<SeMenu> selectAllApi(String serviceCode) {
        return seMenuMapper.selectApiByServiceCode(serviceCode);
    }
}
